package cn.xcstudenth.myapplication.texviewutils;

import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;

import java.lang.ref.WeakReference;

import cn.xcstudenth.myapplication.ConstantUtils;

/**
 * Created by 赵航 on 2020/8/13.
 * WeChat: zhao--hang--
 */
public class TextHtmlUtils {

        /**
         * @param mTextView  要赋值的文本
         * @param content    html文本
         * @param textSize   文字大小
         * @param dayOrNight 日夜间模式
         */
        public static void setHtml(TextView mTextView, String content, int textSize, int dayOrNight) {
            if (content == null) {
                return;
            }
            //更换标签的内容
            String newContent = content.replaceAll(ConstantUtils.SVG, ConstantUtils.IMG);
            //设置文字大小
            // mTextView.setTextSize(textSize);
            WeakReference<TextView> mTextWeakReference = new WeakReference<TextView>(mTextView);
            //仅仅设置点击跳转
            HtmlTagHandler htmlTagHandler = new HtmlTagHandler();

            //获取span
            if (mTextWeakReference.get() != null) {
                HtmlImageGetter htmlImageGetter = new HtmlImageGetter(mTextWeakReference.get(),
                        dayOrNight);
                Spanned spanned = Html.fromHtml(newContent, htmlImageGetter, htmlTagHandler);
                //赋值
                if (mTextWeakReference.get() != null && !TextUtils.isEmpty(spanned)) {
                    mTextWeakReference.get().setText(spanned);
                    //只有设置了这个属性才能够进行点击,但是无图片的时候，才设置点击有效
                    if (content.contains(ConstantUtils.IMG)) {
                        mTextWeakReference.get().setMovementMethod(LinkMovementMethod.getInstance());
                    }
                }
            }

        }
}
